extern crate http;
extern crate httparse;

use std::net::{TcpListener, TcpStream};

use httparse::{Request, Header};

use std::io::{Read, Write};
use std::thread;
use std::time::Duration;

use std::collections::HashMap;

mod tcp;
mod protocol;

use tcp::TcpConnection;

static mut CONNECTION_ID: u32 = 1000000000;


fn main(){
    let listener = TcpListener::bind("0.0.0.0:80").unwrap();
    let mut incoming = listener.incoming();
    let mut buffer = [0u8; 1024];
    loop{
        let stream = incoming.next().unwrap();
        let mut stream = stream.expect("Error handling TCP stream.");

        stream.set_read_timeout(Some(Duration::from_millis(1000)))
              .expect("FATAL: Couldn't set read timeout on socket");
        let result = stream.read(&mut buffer);
        //协议解析
        match result {
            Ok(size) => {
                if size > 0{
                    println!("read bytes size: {:?}", size);
                    protocol::parse(&buffer[..size]);
                    stream.write(&buffer[..size]);
                }
            },
            Err(e) => ()
        }
    }
}


//fn main() {
//    let addr = "0.0.0.0:80".parse().unwrap();
//
//    // Setup the server socket
//    let server = TcpListener::bind(&addr).unwrap();
//
//    // Create a poll instance
//    let poll = Poll::new().unwrap();
//
//    // Start listening for incoming connections
//    poll.register(&server, SERVER, Ready::readable(),
//                  PollOpt::edge()).unwrap();
//
//    // Create storage for events
//    let mut events = Events::with_capacity(1024);
////    let mut connections = HashMap::<u32, TcpConnection>::new();
//    let mut connections = Vec::<TcpStream>::new();
//    let mut user_connections = HashMap::<u32, u32>::new();
//
//    loop {
//        let result = poll.poll(&mut events, Some(Duration::from_millis(1000)));
//
//        match result {
//            Ok(size) => {
//                for event in events.iter() {
//                    println!("event : {:?}", event);
//                    let result = server.accept();
//                    println!("{:?}", result);
//                    if let Ok((mut stream, addr)) = result{
//                        let id = new_connection_id();
////                let connection = TcpConnection::new(id, addr, stream);
//                        //connections.insert(id, connection);
//                        connections.push(stream);
//                    }
//                }
//            }
//            Err(e) => println!("Poll event got an error: {:?}", e)
//        }
//
//        let mut buf = [0u8; 1024];
//
//        for mut conn in &connections{
//            let res = conn.peek(&mut buf);
//            match res {
//                Ok(size) => {
//                    if 0 < size{
//                        println!("{:?}", String::from_utf8_lossy(&buf[0..size]));
//                        conn.write(&buf[0..size]);
//                    }
//                }
//                Err(e) => ()//println!("Read stream got an error: {:?}", e)
//            }

//            let mut headers = [httparse::EMPTY_HEADER; 16];
//            let mut req = httparse::Request::new(&mut headers);
//            println!("req : {:?}", req);
//            let res = req.parse(&buf).unwrap();
//            println!("{:?}", res);
//            if res.is_partial() {
//                match req.path {
//                    Some(ref path) => {
//                        // check router for path.
//                        // /404 doesn't exist? we could stop parsing
//                    },
//                    None => {
//                        // must read more and parse again
//                    }
//                }
//            }
//            if res.is_complete(){
//
//            }
//        }
//    }
//}

fn new_connection_id() -> u32{
    unsafe {
        if CONNECTION_ID > 999999990{
            CONNECTION_ID = 1000000000;
        }
        CONNECTION_ID = CONNECTION_ID + 1;
        CONNECTION_ID
    }
}